# -*-codeing=utf-8-*-

import json
from wsgiref.simple_server import make_server

# 定义函数，参数是函数的两个参数，都是python本身定义的，默认就行了。
def application(environ, start_response):
    headers = [
        ('Content-type', 'text/plain'),
        ('Access-Control-Allow-Origin', '*'),  # 或指定允许访问的域，如 'http://127.0.0.1:8080'
        ('Access-Control-Allow-Methods', 'POST'),  # 允许的请求方法
        ('Access-Control-Max-Age', '3600'),  # 预检请求的有效期，单位秒
    ]
    # 定义文件请求的类型和当前请求成功的code
    start_response('200 OK', [('Content-Type', 'application/json')])

    # environ是当前请求的所有数据，包括Header和URL，body
    print(environ.get("CONTENT_LENGTH", 0))
    # 处理实际请求
    try:
        content_length = int(environ.get("CONTENT_LENGTH", 0))
    except ValueError:
        content_length = 0
    if content_length <= 0:
        # 处理 CONTENT_LENGTH 不存在或无效的情况
        # 可以在这里设置默认值或者返回错误响应
        headers = [('Content-type', 'text/plain')]
        start_response('400 Bad Request', headers)
        return [b'Invalid or missing CONTENT_LENGTH']
    request_body = environ["wsgi.input"].read(int(environ.get("CONTENT_LENGTH", 0)))
    request_body = json.loads(request_body)

    request_data = request_body["test"]
    #print('server...', username)
    import numpy as np
    # 保存文件
    # np.save('file.npy', dict1)
    # 读取文件
    all_data = np.load('file.npy', allow_pickle='TRUE').item()
    #print(new_dict)
    # 逻辑处理 ......
    res = []
    mymap = {"0":"A","1":"B","2":"C","3":"D","4":"E","5":"F","6":"G",'no':'无答案'}
    print(mymap)
    for i in request_data:
        if i in all_data:
            temp = all_data[i].split(",")
        else:
            temp = ['no']
        tmp_res = []
        #print(temp)
        for label in temp:
            tmp_res.append(mymap[label])
        res.append(tmp_res)
    #print(res)
    count = 1
    result = ""
    response_data = {}
    for i in res:
       # print(f"{count}题：{i}")
        result += f"{count}题：{i}\n"
        response_data[f"答案:"]=i
        count+=1
    #result = 'world'
     # 将 JSON 对象转换为字符串
    response_json = json.dumps(response_data, ensure_ascii=False)
    return [response_json.encode('utf-8')]

if __name__ == "__main__":
    port = 6088
    httpd = make_server("0.0.0.0", port, application)
    print("serving http on port {0}...".format(str(port)))
    httpd.serve_forever()


